package be.nvlooy.moviereminder.service.implementations;

import java.util.Map;

import javax.mail.internet.MimeMessage;

import org.apache.velocity.app.VelocityEngine;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.ui.velocity.VelocityEngineUtils;

import be.nvlooy.moviereminder.exception.ServiceException;
import be.nvlooy.moviereminder.service.BasicService;
import be.nvlooy.moviereminder.service.MailService;

public class MailServiceImpl extends BasicService implements MailService {

	private JavaMailSender mailSender;
	
	private VelocityEngine velocityEngine;
	
	private String from;
	
	@Autowired
	public void setMailSender(JavaMailSender mailSender) {
		this.mailSender = mailSender;
	}
	
	@Autowired
	public void setVelocityEngine(VelocityEngine velocityEngine) {
		this.velocityEngine = velocityEngine;
	}
	
	public void setFrom(String from) {
		this.from = from;
	}
	
	@Override
	public void sendMessage(final String to, final String subject, final String template, final Map<String, Object> model) {
		
		 MimeMessagePreparator preparator = new MimeMessagePreparator() {
			 
			public void prepare(MimeMessage mimeMessage) throws Exception {
	            MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
	            message.setTo(to);
	            message.setFrom(from);
	            message.setSubject(subject);
	            String text = VelocityEngineUtils.mergeTemplateIntoString(
	               velocityEngine, "velocity/"+template+".vm", model);
	            
	            message.setText(text, true);
	         }
			
	     };
	     
	     try {
	    	 mailSender.send(preparator);
	     }
	     catch(Exception e) {
	    	 throw new ServiceException("mailSendError" ,e);
	     }
	}	
	
}
